﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MiniFox.Platform;
using MiniFox.Security;
using MiniFox.Web.Infrastructure;
using Wechat.Core;

namespace Wechat.MP.Api
{
    /// <summary>
    /// 微信公众号 API网关（~/wx/svc）
    /// </summary>
    [NoCache]
    public class MpController : WechatControllerBase<IWechatMpService>
    {
        #region 微信验证
        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <param name="echostr"></param>
        /// <returns></returns>
        [HttpGet, AllowAnonymous]
        public override HttpResponseMessage Validate([FromRoute(Name = GlobalKey.NAME)] string name, string signature, string timestamp, string nonce, string echostr)
        {
            var service = this.CreateService(name);
            string token = service.Token;

            string[] arr = { token, timestamp, nonce };
            Array.Sort(arr);
            string temp = string.Join(string.Empty, arr).SHA1EncryptToHexString();
            if (string.Equals(signature, temp, StringComparison.OrdinalIgnoreCase))
            {
                HttpResponseMessage response = new HttpResponseMessage();
                response.Content = new StringContent(echostr);
                return response;
            }
            else
            {
                throw new MiniFox.Exceptions.SystemException("signature:" + temp);
            }
        }
        #endregion

    }
}
